package com.iflytek.jcy.supervise.clue.common.pojo;

import com.iflytek.jcy.supervise.clue.common.enums.ResultEnum;
import com.iflytek.jcy.supervise.clue.common.enums.ResultType;
import lombok.Data;

/**
 * 统一结果对象
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2019-08-06 14:04
 */
@Data
public class CommonResponse {

    /** 状态码 */
    private Integer code;

    /** 请求是否成功 */
    private boolean success;

    /** 状态描述 */
    private String msg;

    /** 数据 */
    private Object data;

    public CommonResponse() {
    }

    public CommonResponse(ResultType resultType) {
        this.code = resultType.getCode();
        this.success = this.code == ResultType.SUCCESS;
        this.msg = resultType.getDesc();
    }

    public CommonResponse(ResultType resultType, Object data) {
        this(resultType);
        this.data = data;
    }

    public CommonResponse(ResultType resultType, String customMsg) {
        this(resultType);
        this.msg = customMsg;
    }

    /** 构造的成功响应 */
    public static CommonResponse success(Object data) {
    	return new CommonResponse(ResultEnum.SUCCESS, data);
    }

    /** 构造无结果的成功响应 */
    public static CommonResponse success() {
        return new CommonResponse(ResultEnum.SUCCESS);
    }

    /** 构造自定义错误信息的默认失败响应 */
    public static CommonResponse failed(ResultType resultType) {
        if (resultType == null || resultType.getCode().equals(ResultType.SUCCESS)) {
            throw new IllegalArgumentException("结果状态枚举必须是失败类枚举");
        }
        return new CommonResponse(resultType);
    }

    /** 构造自定义错误信息的默认失败响应 */
    public static CommonResponse failed(String customMsg) {
        return new CommonResponse(ResultEnum.FAILED, customMsg);
    }

    /** 构造自定义错误码和错误信息的失败响应 */
    public static CommonResponse failed(ResultType resultEnum, String customMsg) {
        return new CommonResponse(resultEnum, customMsg);
    }

    /** 更新状态, 如果为失败则清空 data */
    public CommonResponse update(ResultType resultType) {
        this.code = resultType.getCode();
        this.msg = resultType.getDesc();

        if (!resultType.isSuccess()) {
            this.data = null;
        }
        return this;
    }

    /** 更新状态和描述内容, 如果为失败则清空 data */
    public CommonResponse update(ResultType resultType, String customMsg) {
        // this.update(resultType);
        this.msg = customMsg;
        return this;
    }
}
